<?php

namespace App\Http\Controllers;

abstract class Controller
{
    // 定义模型
    protected $model;

    // 定义构造器
    public function __construct()
    {
        $this->initialize();
    }

    // 定义初始化方法, 子类重写该方法即可保存模型
    protected function initialize() {}

    // 自定义成功响应方法
    protected function success($status = 'success', $data = [], $isObject = false)
    {
        $result = [
            'code'   => 200,
            'status' => $status,
            'data'   => $isObject ? (object)$data : $data
        ];

        return response()->json($result);
    }

    // 自定义成功响应列表数据方法
    protected function successList($status = 'success', $list = [], $total = 0)
    {
        $result = [
            'code'      => 200,
            'status'    => $status,
            'data'      => [
                'list'  => $list,
                'total' => $total
            ]
        ];
        return response()->json($result);
    }

    // 自定义响应失败方法，422: 表示用户请求的数据无法处理
    protected function error($status = 'error', $data = [], $code = 422)
    {
        $result = [
            'code'   => $code,
            'status' => $status,
            'data'   => (object)$data
        ];
        return response()->json($result, $code);
    }
}
